package com.cloud.adrian.novel.user.config;

import com.cloud.adrian.novel.common.auth.JwtUtils;
import com.cloud.adrian.novel.common.auth.UserHolder;
import com.cloud.adrian.novel.common.constant.ErrorCodeEnum;
import com.cloud.adrian.novel.common.constant.SystemConfigConstants;
import com.cloud.adrian.novel.config.exception.BusinessException;
import com.cloud.adrian.novel.user.dto.UserInfoDto;
import com.cloud.adrian.novel.user.manager.cache.UserInfoCacheManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * 认证授权 拦截器：为了注入其它的 Spring beans
 * ，需要通过 @Component 注解将该拦截器注册到 Spring 上下文
 * @Author: xiangguiliang
 * @version: 1.0
 * @since: 2024/05/25
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private final UserInfoCacheManager userInfoCacheManager;

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取登录jwt
        String token = request.getHeader(SystemConfigConstants.HTTP_AUTH_HEADER_NAME);
        // 开始认证
        if (!StringUtils.hasText(token)) {
            // token为空
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        Long userId = JwtUtils.parseToken(token, SystemConfigConstants.NOVEL_FRONT_KEY);
        if (Objects.isNull(userId)) {
            // token解析失败
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        UserInfoDto userInfo = userInfoCacheManager.getUser(userId);
        if (Objects.isNull(userInfo)) {
            // 用户不存在
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_NOT_EXIST);
        }
        // 设置用户信息
        UserHolder.setUserId(userId);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户信息
        UserHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
